<?php

$client_id = get_input('client_id');
$client_secret = get_input('client_secret');

if($client_id != 'draw2gether' || $client_secret != 'iY1s7936788353y') {
    $pro = TRUE;
    if($client_id != 'draw2getherpro' || $client_secret != 'gsQhNvs8VkJ17ML') {
        die(json_encode(export_result(400, "Wrong client: $client_id, $client_secret")));
    }
}

$email = get_input('email');
$facebook_id = get_input('facebook_id');
$fullname = get_input('fullname');
$username = get_input('username');

$result = export_result(200, '');

$user = dt_get_user_by_fb_id($facebook_id);

if ($user) {
    $user_id = $user->user_id;
    $userEntity = get_user($user_id);
} else {
    $user_id = get_user_id_by_email($email);
    if($user_id) {
        $userEntity = get_user($user_id);
    } else {
        $userEntity = get_user_by_email($email);
        if ($userEntity && is_array($userEntity)) {
            $userEntity = array_shift($userEntity); 
            $user_id = $userEntity->guid;
        }
    }
    
    if (!$userEntity) {
        $reg_result = greengar_register($email, $email, $password, $fullname, "", FALSE);
        if ($reg_result['status'] == 200) {
            $user_id = $reg_result['result'];
            $userEntity = get_user($user_id);
        }
    }
    
    if ($userEntity) {
        dt_add_fb_user($userEntity->guid, $facebook_id, $username, $avatar_url, $fullname, $pro);
    }
}

//$userEntity = get_user(2);

if ($userEntity) {
    login($userEntity);
    
    $oauth = oauth2_get_server();
    $result['result'] = $oauth->directlyGrantToken($client_id);
    
    $result['result']['user_id'] = $userEntity->guid;
    
    if($pro) {
        $result['result']['pro'] = dt_pro_coins($user_id);
    } else {
        //$result['result']['lite'] = dt_lite_coins($user_id);
    }
    
    $result['result']['coins'] = dt_export_coins($userEntity->guid);
    
    $purchases = array();

    $references = dt_get_purchases($userEntity->guid);
    foreach ($references as $reference) {
        $purchases[] = $reference->reference;
    }
    
    $result['result']['purchases'] = $purchases;
    
    $reputation = dt_calc_reputation($userEntity->guid);
    $result['result']['reputation'] = $reputation;
} else {
    $result['status'] = 400;
}

echo json_encode($result);
?>
